<template>
  <div class="app-container">
    <div style="margin-bottom: 10px;font-size: 14px;font-weight: normal;font-style: normal; "><span>当前电费支付金额：{{ electric }}&#32;¥</span>&#8195;&#8195;&#8195;
      <span>水费支付金额：{{ water }}&#32;¥</span>
      &#8195;&#8195;&#8195;<span>燃气支付金额：{{ gas }}&#32;¥</span>
      &#8195;&#8195;&#8195;<span>电费归档金额：{{ archiveElectric }}&#32;¥</span>
      &#8195;&#8195;&#8195;<span>水费归档金额：{{ archiveWater }}&#32;¥</span>
      &#8195;&#8195;&#8195;<span>燃气费归档金额：{{ archiveGas }}&#32;¥</span>
    </div>
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-select v-model="listQuery.houseId" filterable placeholder="选择房屋">
        <el-option
          v-for="item in houseOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"/>
      </el-select>

      <el-select v-model="listQuery.costType" filterable placeholder="选择类型">
        <el-option
          v-for="item in costTypeStatusOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"/>
      </el-select>
      <el-button v-permission="['GET /admin/housepay/list']" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button v-permission="['POST /admin/housepay/create']" class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">添加</el-button>
      <el-button
        v-permission="['POST /admin/housepay/create']"
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        style="background-color: #d28d88;border-color: #d28d88;"
        @click="handleArchive">归档
      </el-button>
      <!--<el-button :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">导出</el-button>-->
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row style="width: 100%" row-style="height:35px" cell-style="padding:0" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"/>
      <el-table-column align="center" label="所属房屋" prop="houseId" >
        <template slot-scope="scope">
          {{ formatHouseName(scope.row.houseId) }}
        </template>
      </el-table-column>
      <el-table-column align="center" width="80" label="金额" prop="amount"/>
      <el-table-column align="center" label="支付时间" prop="payTime" sortable/>
      <el-table-column align="center" width="160" label="备注" prop="remark"/>
      <el-table-column align="center" width="100" label="费用类型" prop="costType">
        <template slot-scope="scope">
          <!--<el-tag type="primary" style="margin-right: 20px;"> {{ formatLeaseStatus(scope.row.leaseStatus) }} </el-tag>-->
          <el-tag v-if="scope.row.costType === 0" size="small" type="warning">电费</el-tag>
          <el-tag v-if="scope.row.costType === 1" size="small" type="info">水费</el-tag>
          <el-tag v-if="scope.row.costType === 2" size="small" type="warning">燃气费</el-tag>
          <el-tag v-if="scope.row.costType === 10" size="small" type="warning">已归档电费</el-tag>
          <el-tag v-if="scope.row.costType === 11" size="small" type="info">已归档水费</el-tag>
          <el-tag v-if="scope.row.costType === 12" size="small" type="warning">已归档燃气费</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-permission="['POST /admin/housepay/update']" type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button v-permission="['POST /admin/housepay/delete']" type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">

        <el-form-item label="所属房屋" prop="houseId">
          <el-select v-model="dataForm.houseId" filterable placeholder="请选择">
            <el-option
              v-for="item in houseOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </el-form-item>

        <el-form-item label="金额" prop="amount">
          <el-input v-model="dataForm.amount"/>
        </el-form-item>

        <el-form-item label="支付时间" prop="payTime">
          <el-date-picker
            v-model="dataForm.payTime"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetime"
            placeholder="选择日期"/>
        </el-form-item>
        <el-form-item label="费用类型" prop="costType">
          <el-select v-model="dataForm.costType" filterable placeholder="请选择">
            <el-option
              v-for="item in costTypeStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="dataForm.remark"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #20a0ff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }
  .avatar {
    width: 145px;
    height: 145px;
    display: block;
  }
</style>

<script>
import { listRoom, createRoom, updateRoom, deleteRoom, tatolIncomeRent, archiveIncomeRent } from '@/api/housePay'
import { houseOptions } from '@/api/house'
import { roleOptions } from '@/api/role'
import { uploadPath } from '@/api/storage'
import { getToken } from '@/utils/auth'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

export default {
  name: 'Admin',
  components: { Pagination },
  data() {
    return {
      uploadPath,
      list: null,
      total: 0,
      roleOptions: null,
      electric: null,
      water: null,
      gas: null,
      archiveElectric: null,
      archiveWater: null,
      archiveGas: null,
      houseOptions: null,
      multipleSelection: [],
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        houseId: undefined,
        costType: undefined,
        sort: 'add_time',
        order: 'desc'
      },
      costTypeStatusOptions: [{
        value: 0,
        label: '电费'
      }, {
        value: 1,
        label: '水费'
      }, {
        value: 2,
        label: '燃气费'
      }, {
        value: 3,
        label: '水电费'
      }, {
        value: 10,
        label: '已归档电费'
      }, {
        value: 11,
        label: '已归档水费'
      }, {
        value: 12,
        label: '已归档燃气费'
      }],

      dataForm: {
        // id: undefined,
        // username: undefined,
        // password: undefined,
        // avatar: undefined,
        // roleIds: []
        houseId: undefined,
        costType: undefined,
        amount: undefined,
        payTime: undefined,
        remark: undefined,
        roomRent: 0
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        username: [
          { required: true, message: '管理员名称不能为空', trigger: 'blur' }
        ],
        password: [{ required: true, message: '密码不能为空', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  computed: {
    headers() {
      return {
        'X-Litemall-Admin-Token': getToken()
      }
    }
  },
  created() {
    this.getList()
    roleOptions()
      .then(response => {
        this.roleOptions = response.data.data.list
      })
    houseOptions()
      .then(response => {
        this.houseOptions = response.data.data.list
      })
    tatolIncomeRent()
      .then(response => {
        this.electric = response.data.data.electric
        this.water = response.data.data.water
        this.gas = response.data.data.gas
        this.archiveElectric = response.data.data.archiveElectric
        this.archiveWater = response.data.data.archiveWater
        this.archiveGas = response.data.data.archiveGas
      })
  },

  methods: {
    formatHouseName(houseId) {
      for (let i = 0; i < this.houseOptions.length; i++) {
        if (houseId === this.houseOptions[i].value) {
          return this.houseOptions[i].label
        }
      }
      return ''
    },

    formatRole(roleId) {
      for (let i = 0; i < this.roleOptions.length; i++) {
        if (roleId === this.roleOptions[i].value) {
          return this.roleOptions[i].label
        }
      }
      return ''
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    getList() {
      this.listLoading = true
      listRoom(this.listQuery)
        .then(response => {
          this.list = response.data.data.list
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        houseId: undefined,
        costType: undefined,
        amount: undefined,
        payTime: undefined,
        remark: undefined
      }
    },
    uploadAvatar: function(response) {
      this.dataForm.avatar = response.data.url
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          createRoom(this.dataForm)
            .then(response => {
              this.list.unshift(response.data.data)
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '添加管理员成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }
      })
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          updateRoom(this.dataForm)
            .then(() => {
              for (const v of this.list) {
                if (v.id === this.dataForm.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.dataForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新房间成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('是否确认已删除？', '确认信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        row.delFlag = 1
        updateRoom(row)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
      })
    },
    handleArchive(row) {
      this.$confirm('是否将选择的信息归档？', '确认信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        var ids = this.multipleSelection.map(item => item.id).join()// 获取所有选中行的id组成的字符串，以逗号分隔
        const params = new FormData()
        params.append('ids', ids)
        archiveIncomeRent(params)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '归档成功'
            })
            for (const v of this.list) {
              if (v.id === this.dataForm.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.dataForm)
                break
              }
            }
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
      })
    },
    handleDownload() {
      this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['房间ID', '房间名称', '房间头像']
          const filterVal = ['id', 'username', 'avatar']
          excel.export_json_to_excel2(
            tHeader,
            this.list,
            filterVal,
            '房间信息'
          )
          this.downloadLoading = false
        })
    }
  }
}
</script>
